<template>
  <div class="voucher-main">
    <div class="voucher-header">
      <span class="voucher-no">
        <span class="select-control">
          <el-select v-model="valueSelect">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </span>
        <span>字第</span>
        <span class="voucher-no-ipt">
          <el-input v-model="input" maxlength="5"></el-input>
        </span>
        <span>号</span>
      </span>
      <span class="voucher-date">
        <span>日期：</span>
        <span class="DatePickerInput">
          <el-date-picker v-model="dateValue" type="date" placeholder="">
          </el-date-picker>
        </span>
      </span>
    </div>
    <div class="grid-container">
      <t-table ref="elTable" :table="state.table" :columns="state.table.columns" @cell-click="getCell"
        :row-class-name="tableRowClassName" show-summary :summary-method="getSummaries" :span-method="objectSpanMethod"
        :max-height="tableHeight + 'px'" :isShowPagination="false">
        <template #name="{ scope }">
          <div class="voucher-money-cell-render">
            <div class="label-input"
              v-if="scope.row.index == state.tabRowIndex && scope.column.property == state.tabColumnIndex && scope.row.edit">
              <el-input ref="inputBox" v-model="scope.row[scope.column.property]" type="textarea"
                @input="labelInput(scope)" @change="submit(scope)" @blur="submit(scope)"
                @keydown.enter.native="save($event, scope)"></el-input>
            </div>
            <div class="box_value">{{ scope.row[scope.column.property] }}</div>
          </div>
        </template>
        <template #total="{ scope }">
          <div class="voucher-money-cell-render">
            <div class="digit-input"
              v-if="scope.row.index == state.tabRowIndex && scope.column.property == state.tabColumnIndex && scope.row.edit">
              <el-input ref="inputBox" v-model="scope.row[scope.column.property]" placeholder="0"
                @input="numberInput(scope)" @change="submit(scope)" @blur="submit(scope)"
                @keydown.enter.native="save($event, scope)"></el-input>
            </div>
            <div v-for="(digit, index) in formatNumber(scope.row[scope.column.property])" :key="index"
              class="digit-value" @click="inputType(scope)">{{ digit }}</div>
          </div>
        </template>
      </t-table>
    </div>

    <div class="voucher-footer">
      <div class="label-panel">
        <div class="field">
          <span class="label">制单人：</span>
          <span class="field-val">
            <div style="overflow: hidden; text-overflow: ellipsis;">
              <span>张小墨</span>
            </div>
          </span>
        </div>
        <div class="field">
          <span class="label">审核人：</span>
          <span class="field-val">
            <div style="overflow: hidden; text-overflow: ellipsis;">
              <span></span>
            </div>
          </span>
        </div>
        <div class="field">
          <span class="label">修改人：</span>
          <span class="field-val">
            <div style="overflow: hidden; text-overflow: ellipsis;">
              <span></span>
            </div>
          </span>
        </div>
      </div>
      <div class="btn-panel">
        <t-button type="primary" @click="exportExcel">保存</t-button>
        <t-button type="primary" @click="exportExcel">打印</t-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx" name="pingzhengTable">
import tableData from '../tableData1.json'
import format from '../js/format'
import onChange from '../js/onChange'
// 使用formatNumber
const formatNumber = (number: number | string) => {
  return format.methods.formatNumber(number)
}

const numberToChineseMoney = (number: number | string) => {
  return onChange.methods.numberToChineseMoney(number)
}

const tableHeight = ref('465')
const valueSelect = ref('1')
const input = ref('')
const options = ref([{
  value: '1',
  label: '记'
}])
const dateValue = ref('')


const state: any = reactive({
  value: '', // 区分新增和修改
  table: {
    border: true,
    firstColumn: { type: "index", label: "序列" },
    data: [],
    columns: [
      {
        prop: 'name',
        label: '摘要',
        minWidth: '150',
        canEdit: true,
        configEdit: {
          editSlotName: 'name'
        }
      },
      {
        prop: 'subject',
        label: '会计科目',
        minWidth: '180'
      },
      {
        prop: 'number',
        label: '数量',
        minWidth: '80'
      },
      {
        prop: 'borrowerStart1',
        label: '借方金额',
        minWidth: '180',
        canEdit: true,
        configEdit: {
          editSlotName: 'total'
        },
        renderHeader: (row: any) => {
          return renderVoucherMoney(row)
        }
      },
      {
        prop: 'borrowerStart2',
        label: '贷方金额',
        minWidth: '180',
        canEdit: true,
        configEdit: {
          editSlotName: 'total'
        },
        renderHeader: (row: any) => {
          return renderVoucherMoney(row)
        }
      }
    ],
    operator: [
      {
        text: '复制行',
        render: (text: any, scope: any) => {
          return (
            <el-tooltip effect="dark" content="复制行" placement="top">
              <el-icon class="acitonButton" onClick={() => editCopy(scope)}>
                <DocumentCopy />
              </el-icon>
            </el-tooltip>
          )
        }
      },
      {
        text: '删除行',
        render: (text: any, scope: any) => {
          return (
            <el-popconfirm title="你确定要删除吗？" onConfirm={() => editDel(scope)}>
              {{
                reference: () => (
                  <div>
                    <el-tooltip effect="dark" content="删除行" placement="top">
                      <el-icon class="acitonButton">
                        <Delete />
                      </el-icon>
                    </el-tooltip>
                  </div>
                )
              }}
            </el-popconfirm>
          );
        }
      }
    ],

    // 操作列样式
    operatorConfig: {
      fixed: 'right', // 固定列表右边（left则固定在左边）
      width: 120,
      label: '操作'
    }
  }
})
// 复制行
const editCopy = (scope: any) => {
  console.log('复制行', scope)
  const objAdd = {
    name: scope.name,
    subject: scope.subject,
    number: scope.number,
    borrowerStart1: scope.borrowerStart1,
    borrowerStart2: scope.borrowerStart2
  }
  state.table.data.splice(scope.index + 1, 0, objAdd)
  initEditAttribute() // 复制行后要重新遍历一次添加edit: false
}

// 删除行
const editDel = (scope: any) => {
  console.log('删除', scope)
  state.table.data.splice(scope.index, 1)

  // 创建一个空数组
  const emptyObject = {
    name: '',
    subject: '',
    number: '',
    borrowerStart1: '',
    borrowerStart2: ''
  }

  // 确保至少有5行，不足的话添加空数组
  const adjustedData = state.table.data.length < 5
    ? [...state.table.data, ...Array(5 - state.table.data.length).fill(emptyObject)]
    : state.table.data

  state.table.data = adjustedData
}

// 每个单元格添加edit: false
const initEditAttribute = () => {
  nextTick(() => {
    state.table.data = state.table.data.map((item: any) => {
      return {
        ...item,
        edit: false
      }
    })
  })
}

// 表头数位表公用格式
const renderVoucherMoney = (row: any) => {
  return (
    <div class="voucher-money">
      <div class="voucher-money-cell-label">{row.label}</div>
      <div class="voucher-money-cell-render">
        <div class="digit">
          <div class="digit-cell">百</div>
          <div class="line"></div>
          <div class="digit-cell">十</div>
          <div class="line purple"></div>
          <div class="digit-cell">亿</div>
          <div class="line"></div>
          <div class="digit-cell">千</div>
          <div class="line"></div>
          <div class="digit-cell">百</div>
          <div class="line purple"></div>
          <div class="digit-cell">十</div>
          <div class="line"></div>
          <div class="digit-cell">万</div>
          <div class="line"></div>
          <div class="digit-cell">千</div>
          <div class="line purple"></div>
          <div class="digit-cell">百</div>
          <div class="line"></div>
          <div class="digit-cell">十</div>
          <div class="line"></div>
          <div class="digit-cell">元</div>
          <div class="line red"></div>
          <div class="digit-cell">角</div>
          <div class="line"></div>
          <div class="digit-cell">分</div>
        </div>
      </div>
    </div>
  )
}

// 最终参数获取
const getQueryData = computed(() => {
  const { title, systemName, operName, businessType, status, date } = toRefs(state.queryData)
  return {
    title: title.value,
    systemName: systemName.value,
    operName: operName.value,
    businessType: businessType.value,
    status: status.value,
    beginTime: date.value && date.value[0] ? date.value[0] : null,
    endTime: date.value && date.value[1] ? date.value[1] : null,
    pageNum: state.table.currentPage,
    pageSize: state.table.pageSize
  }
})

onMounted(() => {
  getData()
})

// 获取菜单数据
const getData = () => {
  const res = tableData // 假设有一个异步获取数据的函数
  if (res.success) {
    const originalData = res.table.data

    // 创建一个空数组
    const emptyObject = {
      name: '',
      subject: '',
      number: '',
      borrowerStart1: '',
      borrowerStart2: ''
    }

    // 确保至少有4行，不足的话添加空数组
    const adjustedData = originalData.length < 4 ? [...originalData, ...Array(4 - originalData.length).fill(emptyObject)] : originalData

    state.table.data = adjustedData
  }
}

const elTable = ref()
const objectSpanMethod = () => {
  nextTick(() => {
    // 合计行前3列合并
    if (elTable.value) {
      var current = elTable.value.$el.querySelector(".el-table__footer-wrapper .el-table__footer")
      var cell = current.rows[0].cells;
      cell[0].colSpan = 4;
      cell[0].classList.add('sum_title')
      cell[1].style.display = "none"
      cell[2].style.display = "none"
      cell[3].style.display = "none"
    }
  })
}

const inputBox = ref<HTMLInputElement | null>(null)

// 单元格点击触发事件
const getCell = (row: any, column: any) => {
  console.log('this.tabRowIndex', row)
  console.log('this.tabColumnIndex', column)
  state.tabRowIndex = row.index
  state.tabColumnIndex = column.property
  if (column.property == 'borrowerStart1' || column.property == 'borrowerStart2' || column.property == 'name') {
    row.edit = true
    nextTick(() => {
      if (inputBox.value) {
        inputBox.value.focus() // 使用 ref 来聚焦 inputBox
      }
    })
  }
}

// 把每行的索引放进row中
const tableRowClassName = ({ row, rowIndex }) => {
  row.index = rowIndex
}

// 失去光标
const submit = (scope: any) => {
  // 把输入框隐藏
  scope.row.edit = false
  state.tabRowIndex = null
  state.tabColumnIndex = ''

  // 如果输入的是0或者0.0或者0.00，输入框清空
  if (scope.row[scope.column.property] === '0' || scope.row[scope.column.property] === '0.0' || scope.row[scope.column.property] === '0.00') {
    scope.row[scope.column.property] = ''
  }

  // 发请求把修改的数据发送给后台
  // this.subForm()
}

// 普通输入框
const labelInput = (scope: any) => {
  console.log('普通输入框留着有用', scope)
}

const save = (event: any, scope: any) => {
  console.log('回车键', scope)
  scope.row.edit = false
}
// 汉字合计
const exportTotal = () => {
  const totalValue1 = (Math.round(calculateTotal('borrowerStart1') * 100) / 100).toFixed(2)
  const totalValue2 = (Math.round(calculateTotal('borrowerStart2') * 100) / 100).toFixed(2)

  if (parseFloat(totalValue1) === parseFloat(totalValue2) && (parseFloat(totalValue1) !== 0 || parseFloat(totalValue2) !== 0)) {
    const total = parseFloat(totalValue2)
    return numberToChineseMoney(total)
  } else {
    return ['零元整']
  }
}

// 合计
const getSummaries = (param: { columns: any[]; data: any[] }): any[] => {
  const { columns, data } = param
  const sums: any[] = []

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = (
        <div class="voucher-money-cell-render">
          {`合计：${exportTotal()}`}
        </div>
      )
      return
    }

    const values = data.map((item) => Number(item[column.property]))
    if (column.property === 'borrowerStart1' || column.property === 'borrowerStart2') {
      const totalValue = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + value
        } else {
          return prev
        }
      }, 0)

      // 对于2位小数，将小数部分乘以100，然后取整数部分后再除以100，确保计算精度
      const numAsInt = (Math.round(totalValue * 100) / 100).toFixed(2)
      const numberString = numAsInt.toString()

      sums[index] = (
        <div class="voucher-money-cell-render">
          {formatNumber(numberString)
            .split('')
            .map((digit, idx) => (
              <div class="digit-value" key={idx}>
                {digit}
              </div>
            ))}
        </div>
      )
    } else {
      sums[index] = <div></div>
    }
  })

  return sums
}

const calculateTotal = (property) => {
  const values = state.table.data.map((item) => Number(item[property] || 0))
  return values.reduce((prev, curr) => prev + curr, 0)
}
// 数字输入框,数字输入的格式
const numberInput = (scope: any) => {
  // 如果第一位是0，第二位不是点，就用数字移除以0开头的点
  if (scope.row[scope.column.property].length > 1 && scope.row[scope.column.property].startsWith('0') && scope.row[scope.column.property][1] !== '.') {
    scope.row[scope.column.property] = scope.row[scope.column.property].substring(1)
  }
  // 如果第一位是点，第二位是数字，那么就在点前面加一个0
  if (scope.row[scope.column.property].length > 1 && scope.row[scope.column.property][0] === '.' && !isNaN(scope.row[scope.column.property][1])) {
    scope.row[scope.column.property] = '0' + scope.row[scope.column.property]
  }
  // 限制只能输入一个小数点
  if (scope.row[scope.column.property].indexOf('.') !== -1) {
    const str_ = scope.row[scope.column.property].substr(scope.row[scope.column.property].indexOf('.') + 1)
    if (str_.indexOf('.') !== -1) {
      scope.row[scope.column.property] = scope.row[scope.column.property].substr(0, scope.row[scope.column.property].indexOf('.') + str_.indexOf('.') + 1)
    }
  }
  // 正则替换
  scope.row[scope.column.property] = scope.row[scope.column.property].replace(/^(\d{11})\d+|((\.\d{2})\d+)$/g, '$1$3').replace(/[^0-9.]/g, '') // 保留11位数字和2位小数，只能输入数字
  return scope.row[scope.column.property]
}

// 保存数据区分新增和修改
const inputType = (scope: any) => {
  nextTick(() => {
    state.value = scope.row[scope.column.property]
  })
}

const emit = defineEmits(["exportExcel"])

function exportExcel() {
  emit("exportExcel")
}

</script>

<style lang="scss" scoped>
.voucher-main {
  box-sizing: content-box;
  padding: 0 20px;
  border: 1px solid #dddddd;
  height: 100%;
  background-color: #ffffff;

  .voucher-header,
  .voucher-footer {
    padding: 20px 0;
    position: relative;
    display: flex;
    align-items: center;

    .voucher-no {
      margin-right: 36px;
    }

    .voucher-no-ipt {
      width: 72px;
      display: inline-block;

      :deep(.el-input) {
        height: 32px;
        line-height: 32px;
        text-align: center;
        border: 0;
        border-radius: 0;
        border-bottom: 1px solid #DCDFE6;
      }

      :deep(.el-input__wrapper) {
        box-shadow: unset;
      }
    }

    .select-control {
      width: 85px;
      display: inline-block;

      :deep(.el-select__wrapper) {
        box-shadow: unset;
        border-radius: 0;
        border-bottom: 1px solid #DCDFE6;
      }
    }

    .label-panel {
      .field {
        display: inline-block;
        min-width: 100px;
        margin-right: 20px;
        vertical-align: middle;

        .label {
          display: inline-block;
          vertical-align: middle;
        }

        .field-val {
          display: inline-block;
          vertical-align: middle;
          max-width: 10ch;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }

    .btn-panel {
      flex: 1;
      text-align: right;
      white-space: nowrap;
    }
  }

  .t-table {
    font-family: "Pingfang SC";

    :deep(.el-table--enable-row-hover .el-table__body tr:hover>td.el-table__cell) {
      .cell {
        i.addButton {
          display: block !important;
        }
      }
    }

    :deep(.el-table) {
      .el-table__cell {
        padding: 0;
      }

      .cell {
        padding-left: 0;
        padding-right: 0;

        .acitonButton {
          background-color: #ffffff;
          padding: 6px;
          color: #333333;
          border-radius: 50%;
          font-size: 28px;
          font-weight: 500;

          &:hover {
            background-color: #3662ec;
            color: #ffffff;
          }
        }

        .add_value {
          position: relative;
          width: 50px;
          height: 20px;
          color: #000;
          z-index: 2;

          &::before {
            content: "";
            position: absolute;
            width: 20px;
            height: 20px;
            background: rgb(146, 146, 230);
            border-radius: 100%;
            top: 0;
            bottom: 0;
            margin: auto;
            left: 0;
            right: 0;
            z-index: -1;
          }
        }
      }

      .sum_title {
        .cell {
          font-size: 15px;
          font-weight: 600;
          color: #555555;
          text-align: left;
          padding-left: 14px;
        }
      }

      .el-tooltip {
        width: 100% !important;
      }

      .el-table__footer-wrapper tbody td.el-table__cell {
        background-color: #eff6ff;
      }
    }
  }

  .voucher-money {
    width: 100%;
  }

  :deep(.voucher-money-cell-label) {
    position: relative;
    display: flex;
    line-height: 36px;
    height: 36px;
    width: 100%;
    justify-content: center;
    border-bottom: 1px solid #ebeef5;
  }

  :deep(.voucher-money-cell-render) {
    position: relative;
    display: flex;
    line-height: 60px;
    height: 60px;
    width: 100%;

    .box_value {
      padding: 5px;
      font-size: 12px;
      line-height: 20px;
      font-weight: 600;
      text-align: left;
      width: 100%;
      display: block;
      word-wrap: break-word;
      word-break: break-all;
      white-space: pre-wrap;
      overflow-y: overlay;
    }

    .digit {
      display: flex;
      box-sizing: border-box;
      width: 100%;
      height: 100%;
      align-items: center;

      .digit-cell {
        flex: 1;
        font-size: 12px;
      }

      .line {
        width: 1px;
        height: 60px;
        background-color: #ebeef5;
      }
    }

    .label-input {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: #ffffff;
      z-index: 9;

      :deep(.el-textarea__inner) {
        height: 60px;
        font-family: 'Pingfang SC';
        padding: 5px;
        font-size: 12px;
        line-height: 20px;
        font-weight: 400;
        text-align: left;
        width: 100%;
        display: block;
        word-wrap: break-word;
        word-break: break-all;
        white-space: pre-wrap;
        overflow-y: overlay;
      }
    }

    .digit-input {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: #ffffff;
      z-index: 9;

      .el-input {
        height: 60px;
        line-height: 60px;
        font-size: 24px;
        font-family: "Pingfang SC";
        position: absolute;
        top: 0;
        left: 0;
      }
    }

    .digit-value {
      width: calc(100% / 13);
      line-height: 60px !important;
      height: 60px;
      position: relative;
      font-family: 'Pingfang SC';
      font-size: 20px;
      text-align: center !important;
      padding: 0 !important;

      &:not(:last-child)::after {
        content: '';
        position: absolute;
        width: 1px;
        height: 100%;
        background-color: #ebebeb;
        right: 0;
      }

      &:nth-child(11)::after {
        content: '';
        position: absolute;
        width: 1px;
        height: 100%;
        background-color: #f5605980;
        right: 0;
      }

      &:nth-child(2)::after,
      &:nth-child(5)::after,
      &:nth-child(8)::after {
        content: '';
        position: absolute;
        width: 1px;
        height: 100%;
        background-color: #c0a0f680;
        right: 0;
      }
    }
  }
}

:deep(.el-table) .el-table__body .el-table__row.hover-row {
  position: relative;

  .rowBtns {
    display: block;
  }

  &>.el-table__cell {
    border-top: 0px solid #ebeef5 !important;
    border-right: 1px solid #ebeef5 !important;
    border-bottom: 1px solid #ebeef5 !important;
    border-left: 0px solid #ebeef5 !important;
  }

}
</style>
